<template>
  <div v-loading="loading">
    <assignRole :showAssignRole.sync="showAssignRole" :userId="userId" ref="assignRole"></assignRole>
    <addEmployee
      :dialogFormVisible.sync="dialogFormVisible"
      @getRole="getEmployee"
    ></addEmployee>
    <PageTools>
      <template v-slot:before>
        <div>共{{ total }}条记录</div>
      </template>
      <template slot="after">
        <el-button size="small" type="warning" @click="switchImport"
          >excel导入</el-button
        >
        <el-button size="small" type="danger" @click="exportExcel(true)"
          >导出</el-button
        >
        <el-button size="small" type="primary" @click="addEmployee"
          >新增员工</el-button
        >
      </template>
    </PageTools>
    <!-- 放置表格和分页 -->
    <el-table border :data="employee">
      <el-table-column label="序号" sortable="" type="index" />
      <el-table-column label="姓名" sortable="" prop="username" />
      <el-table-column label="头像" sortable="">
        <template slot-scope="{ row }">
          <img
            :src="row.staffPhoto"
            alt=""
            style="width: 40px; height: 40px"
            v-imagerror="defaultImg"
            @click="showQrCode(row.staffPhoto)"
          />
        </template>
      </el-table-column>

      <el-table-column label="工号" sortable="" prop="workNumber" />
      <el-table-column
        label="聘用形式"
        sortable=""
        prop="formOfEmployment"
        :formatter="formatter"
      />
      <el-table-column label="部门" sortable="" prop="departmentName" />
      <el-table-column label="入职时间" sortable="">
        <template slot-scope="{ row }">
          {{ row.timeOfEntry | formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="账户状态" sortable="">
        <template slot-scope="{ row }">
          <el-switch
            :value="row.enableState == 1"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" sortable="" fixed="right" width="280">
        <template slot-scope="{ row }">
          <el-button type="text" size="small" @click="goDetail(row)"
            >查看</el-button
          >
          <el-button type="text" size="small">转正</el-button>
          <el-button type="text" size="small">调岗</el-button>
          <el-button type="text" size="small">离职</el-button>
          <el-button type="text" size="small" @click="alertRole(row.id)">角色</el-button>
          <el-button type="text" size="small" @click="deleteEmployee(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-row type="flex" justify="center" align="middle" style="height: 60px">
      <el-pagination
        layout="prev, pager, next"
        :page-size="page.pagesize"
        :current-page="page.page"
        :total="total"
        :background="true"
        @current-change="changePage"
      />
    </el-row>
    <!-- 头像弹框 -->
    <el-dialog :visible="showAvar" @close="showAvar=false" style="text-align:center;">
      <canvas ref="avar"></canvas>
    </el-dialog>
  </div>
</template>

<script>
import assignRole from "./assignRole"
import QrCode from "qrcode"
import addEmployee from "./addEmployee";
import dayjs from "dayjs";
import { getEmployeeList, delEmployee} from "@/api/employees";
export default {
  name: "employees",
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      userId:0,
      showAssignRole:false,
      showAvar: false,
      defaultImg: require("@/assets/common/bigUserHeader.png"),
      loading: false,
      dialogFormVisible: false,
      page: {
        page: 1,
        pagesize: 10,
      },
      total: 0,
      employee: [],
    };
  },
  filters: {
    // 使用过滤器和dayjs进行日期格式化。
    formatDate(time) {
      // console.log("time",time);
      let result = dayjs(time).format("YYYY-MM-DD");
      //    console.log(result);
      return result;
    },
  },
  created() {
    this.getEmployee();
  },
  methods: {
    // index序号，cellvalue，字段的值，
    // 利用el-table的formatter属性的回调来格式化内容
    formatter(row, column, cellValue, index) {
      // console.log("22",row,column,cellValue,index);
      return cellValue == 1 ? "正式" : "非正式";
    },
    async getEmployee() {
      try {
        this.loading = true;
        let result = await getEmployeeList(this.page);
        console.log(result);
        this.employee = result.rows;
        this.total = result.total;
        this.loading = false;
      } catch (error) {
        console.log(error.message);
        this.loading = false;
      }
    },
    deleteEmployee(id) {
      this.$confirm("确定删除该员工吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await delEmployee(id);
          console.log(result);
          this.$message({
            type: "success",
            message: "删除成功！",
          });
          this.changePage(this.page.page);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "删除失败！",
          });
        });
    },
    changePage(page) {
      console.log(page);
      this.page.page = page;
      this.getEmployee();
    },
    // 添加新员工按钮触发
    addEmployee() {
      this.dialogFormVisible = true;
    },

    // switchImport导入
    switchImport() {
      this.$router.push({
        path: "/import",
      });
    },
    // excel导出处理数据
    formatJson(headers, rows) {
      // 对第一层的数组进行遍历
      // {
      //             "id": "604f764971f93f3ac8f365c2",
      //             "mobile": "13800000002",
      //             "username": "管理员3",
      //             "password": "e10adc3949ba59abbe56e057f20f883e",
      //             "timeOfEntry": "2018-11-02",
      //             "formOfEmployment": 1,
      //             "workNumber": "9002",
      //             "correctionTime": "2018-11-30",
      //             "departmentName": "总裁办",
      //             "staffPhoto": "http://q6cu3t6jv.bkt.clouddn.com/1063705989926227968?t=1616204161907"
      //         }
      // 转化成
      // ["604f764971f93f3ac8f365c2","13800000002", "管理员3"]
      // [[],[],[]]
      return rows.map((item) => {
        //   Object.values(headers) ['username', 'mobile', 'formOfEmployment']
        // ["604f764971f93f3ac8f365c2","13800000002", "管理员3"]
        return Object.values(headers).map((value) => {
          // 此时value就是 字段名
          // item[value] 对应的就是 13800000002 -管理员3 -2018-11-02
          // 需要针对几个字段处理- 聘用形式
          if (value === "formOfEmployment") {
            // 当字段为聘用形式时 需要知道其值所对应的真的文本
            // 寻找聘用形式对应的文本内容
            return item[value] == "1" ? "正式" : "非正式";
          } else if (value === "timeOfEntry" || value === "correctionTime") {
            // 当字段是日期时
            return dayjs(item[value]).format("YYYY-MM-DD");
          }
          return item[value];
        });
      });
    },
    // excel导出
    async exportExcel(isComplex) {
      console.log(isComplex);
      let headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      // 导出excel
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.total,
      });
      // console.log(this);
      let data = this.formatJson(headers, rows); // 返回的data就是 要导出的结构
      console.log("data",data);
      // console.log(data);
      import("@/utils/export2").then((excel) => {
        //  excel是引入文件的导出对象
        // 导出  header从哪里来
        // data从哪里来
        // 现在没有一个接口获取所有的数据
        // 获取员工的接口 页码 每页条数    100   1 10000

        let multiHeader = isComplex
          ? [["姓名", "主要信息", "", "", "", "", "部门"]]
          : [];
        const merges = isComplex ? ["A1:A2", "B1:F1", "G1:G2"] : [];
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: "员工资料表",
          multiHeader, // 复杂表头
          merges, // 合并选项
        });
      });
    },
    // 点击查看跳转详情页。
    goDetail(row) {
      console.log(row);
      this.$router.push({
        path: "/employees/detail/" + row.id,
      });
    },
    // 点击头像弹出二维码
    showQrCode(url) {
      // url存在的情况下 才弹出层
      console.log(url);
      if (url) {
        this.showAvar = true; // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.avar, url); // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        });
      } else {
        this.$message.warning("该用户还未上传头像");
      }
    },
    // 角色
    alertRole(id){
      this.showAssignRole = true;
      this.userId = id;
      this.$refs.assignRole.getRoleList();
      this.$refs.assignRole.getRole(id);
    },

  },
};
</script>

<style>
</style>